package com.banksoft.front.util;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;

/**
 * 图片合成，水印
 * Created by Administrator on 2016/10/7.
 */
public class ImageDrawUtil {

    /**
     * 把图片印刷到底图上面，
     * @param pressImg   需要印刷的图标
     * @param targetImg  底图
     * @param left   左边距离
     * @param top  右边距离
     */
    public final static void pressImage(String pressImg, String targetImg, int left, int top) {
        try {
            //目标文件
            File _file = new File(targetImg);
            Image src = ImageIO.read(_file);
            int wideth = src.getWidth(null);
            int height = src.getHeight(null);
            BufferedImage image = new BufferedImage(wideth, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics g = image.createGraphics();
            g.drawImage(src, 0, 0, wideth, height, null);
            //水印文件
            File _filebiao = new File(pressImg);
            Image src_biao = ImageIO.read(_filebiao);
            int wideth_biao = src_biao.getWidth(null);
            int height_biao = src_biao.getHeight(null);
            if(left == -1) {
                left = (wideth - wideth_biao) / 2;
            }
            if(top == -1) {
                top = (height - height_biao) / 2;
            }
            g.drawImage(src_biao, left,
                    top, wideth_biao, height_biao, null);
            //水印文件结束
            g.dispose();
            FileOutputStream out = new FileOutputStream(targetImg);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(image);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
